#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time      :2021/11/2 9:34
# @Author    :cjw
from typing import Optional

from requests import Response

from use_custom_api.base.base_api import BaseApi
from use_custom_api.setting import FEISHU_URL, APP_ID, APP_SECRET, TENANT_ACCESS_TOKEN
from use_custom_api.util.log import logging


class FeiShuApi(BaseApi):
	token: Optional[str] = None
	base_url: str = FEISHU_URL

	def __init__(self):
		# 初始化时，首先判断token的值是否为空
		if not self.token:
			self.token = self.get_token

	def fs_request(self, data: dict) -> Response:
		# 增加请求头数据
		headers = {
			'Authorization': f'Bearer {self.token}',
			'Content-Type': 'application/json; charset=utf-8'
		}
		data.update(headers=headers)
		return self.request(data)

	@property
	def get_token(self) -> str:
		"""获取token"""
		# token请求数据
		# 具体的api对象通过这样的设计，可以实现数据化，为以后的自动化生成案例奠定了基础
		data = {
			'method': 'POST',
			'url': TENANT_ACCESS_TOKEN,
			'json': {
				'app_id': APP_ID,
				'app_secret': APP_SECRET
			}
		}
		token = self.request(data).json().get('tenant_access_token')
		logging.info(f'获取到的token：{token}')
		return token
